package com.wzh.glsc.auth.service.impl;

import com.wzh.common.constant.AuthServerConstant;
import com.wzh.common.exception.BizCodeEnume;
import com.wzh.common.utils.R;
import com.wzh.glsc.auth.feign.MemberFeignService;
import com.wzh.glsc.auth.feign.SmsFeignService;
import com.wzh.glsc.auth.service.LoginService;
import com.wzh.glsc.auth.to.UserRegisterTo;
import com.wzh.glsc.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.auth.service.impl
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    SmsFeignService smsFeignService;
    @Resource
    MemberFeignService memberFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R sendCode(String phone) {
        //取出验证码
        String code = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        //接口防刷
        if(StringUtils.isNotEmpty(code)){
            //取出验证码的以_分隔的存储时间并转成Long值
            Long temp=Long.parseLong(code.split("_")[1]);
            //当时系统是以毫秒为单位,所以-6W毫秒也就是60秒
            if(System.currentTimeMillis()-temp<60000){
                return R.error(BizCodeEnume.SMS_REPEAT_EXCEPTION.getCode(),
                        BizCodeEnume.SMS_REPEAT_EXCEPTION.getMsg());
            }
        }
        code =String.valueOf((int)((Math.random()*9+1)*100000));
        R r = smsFeignService.sendCode(phone, code);
        if(r.getCode()==0){
            //存储key code  并设置过期时间为10分钟,
            //code 存储当前系统时间用_分隔
            redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX +phone,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error("sms短信服务出现异常");
        }
    }

    @Override
    public R register(UserRegistVo userRegistVo) {
        UserRegisterTo userRegisterTo=new UserRegisterTo();
        BeanUtils.copyProperties(userRegistVo, userRegisterTo);
        return memberFeignService.register(userRegisterTo);
    }

    @Override
    public boolean codeRight(UserRegistVo userRegistVo){
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        if(redisCode!=null){
            redisCode = redisCode.split("_")[0];
            if(redisCode.equals(userRegistVo.getCode())){
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
                return true;
            }
        }
        return false;
    }
}
